﻿<?php

class mCustomer
{
	public $rows = null;
	private $phones = null;

	public function __construct()
	{
		$this->Load();
		$this->LoadPhones();

	}

	private function Load()
	{
		global $DB;
		$sql = "SELECT id, title, contacts, addr FROM customers ORDER BY title";
		$this->rows = $DB->select($sql);
	}

	private function LoadPhones()
	{
		global $DB;
		$sql = "SELECT id, customer_id, phone, note FROM customer_phones ORDER BY phone";
		$this->rows = $DB->select($sql);
	}

	public function GetPhones($customer)
	{
		$found_phones = array();
		foreach ($this->phones as $phone) {
			if($customer["id"] == $phone["customer_id"])
			{
				array_push($found_phones, $phone);
			}
		}
		return $found_phones;
	}

	public function GetCustomersByPhonePattern($phone_pattern)
	{
		// заполняется список ID заказчиков по части номера телефона
		$customer_id_list = array();
		if($this->phones)
		{
			foreach ($this->phones as $phone) 
			{
				if(strpos($phone["phone"], $phone_pattern) !== false)
				{
					if(!in_array($phone["customer_id"], $customer_id_list))
					{
						array_push($customer_id_list, $phone["customer_id"]);
					}
				}
			}
		}

		// заполняется список свойств заказчиков по списку их ID
		$found_customers = array();
		foreach ($this->rows as $customer) 
		{
			if(in_array($customer["id"], $customer_id_list))
			{
				array_push($found_customers, $customer);
			}
		}

		return $found_customers;
	}

}

